﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Net;
using System.Xml;
using System.IO;

namespace Readify.Management.Automation.GoGrid
{
    [Cmdlet("Get", "GoGridIPAddress")]
    public class GetGoGridIPAddressCmdlet : Cmdlet
    {
        [Parameter(Mandatory = true)]
        public PSCredential Credential { get; set; }

        [Parameter()]
        public SwitchParameter Public { get; set; }

        [Parameter()]
        public SwitchParameter Unassigned { get; set; }

        protected override void ProcessRecord()
        {
            string url = this.BuildUrl();

            XmlDocument document = GoGridHelper.ProcessRequest(url, this);
            XmlNodeList objectElementNodeList = document.SelectNodes("/gogrid/response/list/object[@name = 'ip']");

            foreach (XmlNode objectElementNode in objectElementNodeList)
            {
                GoGridIPAddress address = GoGridIPAddress.CreateFromXmlNode(objectElementNode);
                this.WriteObject(address);
            }
        }

        private string BuildUrl()
        {
            string url = this.BuildBasicUrl();
            url = this.AppendPublicModifierIfNecessary(url);
            url = this.AppendUassignedModifierIfNecessary(url);
            return url;
        }

        private string AppendUassignedModifierIfNecessary(string url)
        {
            if (this.Unassigned) url += "&ip.state=unassigned";
            return url;
        }

        private string AppendPublicModifierIfNecessary(string url)
        {
            if (this.Public) url += "&ip.type=public";
            return url;
        }

        private string BuildBasicUrl()
        {
            string urlFormat = "https://api.gogrid.com/api/grid/ip/list?api_key={0}&sig={1}&v=1.0&format=xml";

            NetworkCredential credential = this.Credential.GetNetworkCredential();
            string apiKey = credential.UserName;
            string secret = credential.Password;

            string signature = GoGridHelper.GenerateRequestSignature(apiKey, secret);

            string basicUrl = string.Format(urlFormat, apiKey, signature);
            return basicUrl;
        }
    }
}
